jQuery(function(){	
	//DD_roundies.addRule('.bogoc', '5px', true);		
	
	var $updatingPercentLink = null;
	
	var doingGoalCache = new Array();	
	var $doingPage = jQuery("div#doing div.page");
	var $doingPageLoader = jQuery("div#doing_paging_loader");
	var $doingNextButton = jQuery("a#next_doing");
	var $doingPrevButton = jQuery("a#prev_doing");	
	
	var doneGoalCache = new Array();	
	var $donePage = jQuery("div#done div.page");
	var $donePageLoader = jQuery("div#done_paging_loader");
	var $doneNextButton = jQuery("a#next_done");
	var $donePrevButton = jQuery("a#prev_done");
	
	bindDoingListPaging();
	bindDoneListPaging();
	
	function bindDoingListPaging(){
		var keyValues = {
		   "userId": $doingNextButton.attr("name"),
		   "status" : "USING",
		   "goalStatus": "DOING"
		};
		var orderProperty = "updateDate";
		bindGoNext($doingNextButton, $doingPrevButton, doingGoalCache, $doingPage, $doingPageLoader, 
					keyValues, orderProperty);
		bindGoPrev($doingPrevButton, doingGoalCache, $doingPage, $doingPageLoader);
	}
	
	function bindDoneListPaging(){
		var keyValues = {
		   "userId": $doneNextButton.attr("name"),
		   "status" : "USING",
		   "goalStatus": "FINISHED"
		};
		var orderProperty = "updateDate";
		bindGoNext($doneNextButton, $donePrevButton, doneGoalCache, $donePage, $donePageLoader, 
					keyValues, orderProperty);
		bindGoPrev($donePrevButton, doneGoalCache, $donePage, $donePageLoader);
	}
		
	function bindGoNext($next, $prev, cache, $page, $loader, keyValues, orderProperty){
		$next.click(function(){
			var $this = $next;
			
			$page.slideUp();
			$loader.fadeIn();
			
			var prevPage = $prev.attr("rel");
			prevPage = parseInt(prevPage);
			var nextPage = prevPage + 2;
			
			if(nextPage < cache.length){
				var pageContent = cache[nextPage];							
				$page.html(pageContent);							
				$prev.attr("rel", nextPage-1);
				
				$page.slideDown();
				$loader.fadeOut();
			}else{
				var lastOrderPropertyValue = $next.attr("rel");
				PagingManager.getPage(1, keyValues, orderProperty, lastOrderPropertyValue, function(result){
					if(result != null){
						//var $page = jQuery("div#doing div.page");
						var lastItemIndex = $page.find("div.listnumber:last").html();
						var pageItems = result.pageItems;
						var pageItem, html;
						var cacheLength = cache.length;				
						
						if(result.pageItems.length == 0){
							cache[cacheLength]=$page.html();
							$next.unbind('click').click(function(){
								var $this = jQuery(this);
								
								$page.slideUp();
								$loader.fadeIn();
								
								var gotoPage = $prev.attr("rel");						
								gotoPage = parseInt(gotoPage)+2;
								if(gotoPage < cache.length){
									var pageContent = cache[gotoPage];							
									$page.html(pageContent);							
									$prev.attr("rel", gotoPage-1);
								}
								
								$page.slideDown();
								$loader.fadeOut();
								
								return false;
							});
							
							var gotoPage1 = $prev.attr("rel");						
							gotoPage1 = parseInt(gotoPage1)+2;
							if(gotoPage1 < cache.length){
								var pageContent = cache[gotoPage1];							
								$page.html(pageContent);							
								$prev.attr("rel", gotoPage1-1);
							}
							
							$page.slideDown();
							$loader.fadeOut();
							
							return;
						}				
						
						lastItemIndex = parseInt(lastItemIndex)+1;
						cache[cacheLength]=$page.html();
						$prev.attr("rel",cacheLength);
						$page.html("");
						
						for(var i=0; i<pageItems.length; i++){
							pageItem = pageItems[i];
							html = buildGoalProgress(i+lastItemIndex, pageItem);
							$page.append(html);
						}
						$next.attr("rel", pageItem.updateDate);
						$loader.fadeOut();
						$page.slideDown();
						
						bindShowActionControl();
					}
				});
			}
			
			return false;
		});
	}
	
	function bindGoPrev($prev, cache, $page, $loader){
		$prev.click(function(){
			var $this = $prev;
			var gotoPage = $this.attr("rel");
			gotoPage = parseInt(gotoPage);
			var pageContent = cache[gotoPage];
			
			if(gotoPage < 0)
				return false;
			
			if(cache.length < parseInt(gotoPage)+2){
				cache[gotoPage+1] = $page.html();
			}
					
			$page.slideUp();
			$loader.fadeIn();
			$page.html(pageContent);
			$loader.fadeOut();
			$page.slideDown();
			if(gotoPage >= 0){
				gotoPage = gotoPage -1;
			}
			$this.attr("rel", gotoPage)
			
			return false;
		});
	}
	function buildGoalProgress(index, pageItem){
		var html = jQuery("div#goal_list_placeholder").html();
		var percentPX = '<div class="center" style="width:'+pageItem.percent*183/100+'px"></div>';
		html = html.replace("@[index]@", index);
		html = html.replace(/\@\[goalId\]\@/g, pageItem.goalId);
		html = html.replace(/\@\[title\]\@/g, pageItem.title);
		html = html.replace(/\@\[entryCount\]\@/g, pageItem.entryCount);
		html = html.replace(/\@\[percent\]\@/g, pageItem.percent);
		html = html.replace(/\@\[percentPX\]\@/g, percentPX);
		html = html.replace(/\@\[userCount\]\@/g, pageItem.userCount);
		
		html = parseOperator(html, pageItem);
		return html;
	}
	
	function parseOperator(html, pageItem){
		var flag = true;
		while(flag){
			var startIfPos = html.indexOf("@[if_");
			if(startIfPos < 0){
				return html;
			}
			var endStartIfPos = html.indexOf("]@");
			
			var operatorClause = html.substring(startIfPos+5, endStartIfPos);
			var items = operatorClause.split(";");
			if(items.length < 3)
				continue;
			
			var startEndIfPos = html.indexOf("@[/if_" + items[0]);
			if(startEndIfPos < 0){
				return html;
			}	
			
			var operator = "==";
			if(items[1] == "gt"){
				operator = ">";
			}else if(items[2] == "lt"){
				operator = "<";
			}
			var clause = "var rs = pageItem."+items[0]+operator+"'"+items[2]+"'"; 
			eval(clause);
			if(rs == false){
				html = html.substring(0, startIfPos) + html.substring(startEndIfPos+items[0].length+8);
			}else{
				html = html.substring(0, startIfPos) + html.substring(endStartIfPos+2, startEndIfPos) + html.substring(startEndIfPos+items[0].length+8); 
			}
		}
	}
	
	jQuery("a#prev_doing").click(function(){
		return false;
	});
	
	bindSlider();
	
	function bindSlider(){
		jQuery("a.updateGoalStatus").each(function(){
			var $this = jQuery(this);
			$this.fancybox({
				onStart: function(){
					$updatingPercentLink = $this;
					var data = $this.attr("rel").split(";");
					var goalId = data[0];
					var percent = data[1];
					var selector = jQuery("#slider").attr("rel");
					
					//map data to close button
					jQuery("div#closeSlider a").attr("rel",data);
					
					jQuery(selector).css({position: 'absolute', left: percent+"%"});
					jQuery(selector).html(percent+'%');
					jQuery("#slider").slider({
						range: "min",
						value: percent,
						min: 0,
						max: 100,
						slide: function(event, ui) {
							var $handle = jQuery(ui.handle);
							var val = $handle.css("left");
							jQuery(selector).css({position: 'absolute', left: val});
							jQuery(selector).html(ui.value + '%');
						},
						change: function(event, ui) {
							var $handle = jQuery(ui.handle);
							var val = $handle.css("left");
							if(val.length == 3){
								var num = val.substring(0,2);
								num = parseInt(num)-0.5;
								val = num + "%";
							}else if(val.length == 4){
								var num = val.substring(0,3);
								num = parseInt(num)-1;
								val = num + "%";
							}
							jQuery(selector).css({position: 'absolute', left: val});
							jQuery(selector).html(ui.value + '%');
							jQuery("div#closeSlider a").attr("rel",goalId+";"+ui.value);
						}
					});
				}
			});	
		});
		
		jQuery("div#closeSlider a").unbind('click').click(function(){
			var $this = jQuery(this);
			var data = $this.attr("rel").split(";");
			var goalId = data[0];
			var percent = data[1];
			var $result = jQuery("div.scorebar[rel="+goalId+"]");
			var $resultNum = jQuery("div.scoredo[rel="+goalId+"] b");
			
			GoalManager.updateUserGoalPercent(goalId, percent, function(){
				var percentPX = 183*percent/100 + "px";
				if(jQuery.trim($result.html())==""){
					$result.append('<div class="left"></div><div class="center" style="width:'+percentPX+';"></div><div class="right"></div>');
				}else{
					$result.children("div.center").css("width", percentPX);
				}			
				$resultNum.html(percent);
				$this.attr("rel","");
				$updatingPercentLink.attr("rel",goalId+";"+percent);
				jQuery.fancybox.close();
			});		
			
			return false;
		});
	}		
	
	// edit entry
//	jQuery(".edit_entry_pop").click(function() {
//		rel = jQuery(this).attr("rel");
//		jQuery("#entry_holder_" + rel).hide();
//		jQuery("#edit_entry_holder_" + rel).show();
//	});
	
	function blockAddGoalInput(){
		jQuery("input#newGoalTitle").iBlock({img: '/images/ajaxloading.gif'});
		jQuery("input[type=button]#add_goal").iBlock({});
	}
	
	function unblockAddGoalInput(){
		jQuery("input#newGoalTitle").iUnblock();
		jQuery("input[type=button]#add_goal").iUnblock();
	}
	
	function onDeleteClick(){
		var $this = jQuery(this);
		var $parent = $this.parents(".goal_list");
		var $noGoalParent = $parent.parent("#doing");
		jConfirm('Bạn vừa thực hiện xóa một nội dung nào đó. Nếu chắc chắn với việc thực hiện này, vui lòng nhấn nút <b>Xác nhận</b> ở dưới!', 'Xác nhận', function(r){
			if(r == true){
				GoalManager.removeGoal($this.attr("rel"), function(result){
					if(result != -1){
						$parent.next("div.w3").remove();
						$parent.remove();
						var index = 1;
						jQuery("#doing .goal_list .listnumber").each(function(){
							jQuery(this).html(index);
							index++;
						});
						if(index == 1){
							//no more goal
							html = '<div class="clear"></div><div class="NoGoal"><span class="icon_1 iconNoGoal"></span><p>Hiện tại bạn <b>chưa xác định</b> bất cứ mục tiêu nào cho mình.<br/> Hãy <b>nhập mục tiêu</b> và thực hiện nó nhé!</p></div>';
							$noGoalParent.append(html);
						}
					}
				});
			}
		});
		return false;
	}
	
	jQuery("input#newGoalTitle").keydown(function(e){		
		if(e.keycode == 13 || e.which == 13){
			if(!jQuery(this).hasClass('ignore_me') && jQuery("div.goalSuggestion").css("display") == "none"){								
				addNewGoal();
			}
		}
	});
	
	jQuery("div.dbAddGoal a#add_goal").click(function(){
		if(jQuery(this).hasClass('ignore_me')){
			return false;
		}
		
		addNewGoal();		
		return false;
	});
	
	function addNewGoal(){
		var $newGoal = jQuery("input#newGoalTitle");
		if($newGoal.attr("rel") == 'deny'){
			var $content = buildFailedNotice('Thêm mục tiêu không thành công!','Số lượng mục tiêu để bạn thêm vào danh sách hôm nay đã hết. <b>Hãy thêm vào trong thời gian tới</b>.'); 
			jQuery("div#addGoalResult").unbind();
			jQuery("div#addGoalResult").html($content).css('margin-bottom', '15px').fadeIn(2000).delay(5000).fadeOut(1000);
			return;
		}
		
		$newGoal.blur();
		var newGoal = jQuery("input#newGoalTitle").val();
		if(newGoal == null || jQuery.trim(newGoal) == ""){
			alert("Hãy nhập ít nhất 1 ký tự.");
			jQuery("input#newGoalTitle").focus();
			return;
		}
		newGoal = jQuery.trim(newGoal);
		var goalDTO = {
			title: newGoal
		};
		
		blockAddGoalInput();
		
		GoalManager.isThisGoalInUserGoalList(goalDTO, {
			callback: function(result){
				if(result==false){
					jQuery("form[name=data]").submit();
				}else{
					unblockAddGoalInput();
					var $content = buildFailedNotice('Thêm mục tiêu không thành công!', 'Mục tiêu bạn vừa thêm vào trùng với một trong số những mục tiêu bạn đã thêm. <b>Hãy kiểm tra lại!</b>');
					jQuery("div#addGoalResult").unbind();
					jQuery("div#addGoalResult").html($content).css('margin-bottom', '15px').fadeIn(2000).delay(1000).slideUp("slow");
				}
			},
			exceptionHandler: function(message, exception) {			
				unblockAddGoalInput();
				var $content = buildFailedNotice('Thêm mục tiêu không thành công!', 'Mục tiêu bạn vừa thêm vào trùng với một trong số những mục tiêu bạn đã thêm. <b>Hãy kiểm tra lại!</b>');
				jQuery("div#addGoalResult").unbind();
				jQuery("div#addGoalResult").html($content).css('margin-bottom', '15px').fadeIn(2000).delay(1000).slideUp("slow");
		    }
		});		
	}
	
	var waitingLoadDoing = false;
	var waitingLoadDone = false;
	
	jQuery("div.goalProcessTab a.leftTab").click(function(){
		var $this = jQuery(this);
		if(!$this.hasClass("selected")){
			$this.addClass("selected");
			jQuery("div.goalProcessTab a.rightTab").removeClass("selected");
			jQuery("div#goal_info div#done").hide();
			jQuery("div#loader").show();
			waitingLoadDoing = true;
			setTimeout(showDoingGoals, 300);
		}
		return false;
	});
	
	jQuery("div.goalProcessTab a.rightTab").click(function(){
		var $this = jQuery(this);
		if(!$this.hasClass("selected")){
			$this.addClass("selected");
			jQuery("div.goalProcessTab a.leftTab").removeClass("selected");
			jQuery("div#goal_info div#doing").hide();
			jQuery("div#loader").show();
			waitingLoadDone = true;
			setTimeout(showDoneGoals, 300);
		}
		return false;
	});
	
	function showDoingGoals(){
		if(waitingLoadDone == true){
			waitingLoadDoing = false;
			return;
		}
		jQuery("div#loader").hide();
		jQuery("div#goal_info div#doing").show();
		waitingLoadDoing = false;
	}
	
	function showDoneGoals(){
		if(waitingLoadDoing == true){
			waitingLoadDone = false;
			return;
		}
		jQuery("div#loader").hide();
		jQuery("div#goal_info div#done").show();
		waitingLoadDone = false;
	}
	
	jQuery("textarea.elastic").elastic();
	
	function resetDoingGoalListNumber(){
		var index=2;
		jQuery("#doing .goal_list .listnumber").each(function(){
			jQuery(this).html(index);
			index++;
		});
	}
	
	jQuery("div.dashboard_group_quote_content_Comment_content_align").hide();
	jQuery("li.dashboard_group_quote_content_settings_tools_comment").click(function(){
		var $div = jQuery("div.dashboard_group_quote_content_Comment_content_align");
		if($div.hasClass("open")){
			$div.slideUp().removeClass("open").addClass("close");
		}else{
			$div.slideDown().removeClass("close").addClass("open");			
		}
	});
		
	function buildNewGoalProcessHTML(id, number, title, entryCount, status, userCount){
		status = 'HOÀN THÀNH';
		html = '<div class="goal_list"><div class="listnumber">${0}</div><div class="listGoal">';
		html += '<a class="listname" rel="${5}" href="/goal/view/${5}" title="${1}">${_1}</a>';                             
		html += '<div class="dropicon"><div class="icon1"><div class="hide">';
		html += '<a class="makeItDone" rel="${5}" href="/done/edit/${5}"><div class="text">Hoàn thành mục tiêu</div></a>'; 
		html += '<a class="deleteGoal" rel="${5}"><div class="text">Xóa mục tiêu</div></a>';
		html += '<a class="updateGoalStatus" rel="${5};0" href="#sliderPopup"><div class="text">Cập nhật mục tiêu</div></a>'; 
		html += '<a class="writeGoalEntry" rel="${5}"><div class="text" onclick="window.location.href=\'/entry/add/${5}\'">Viết bài cập nhật</div></a>'; 
		html += '</div></div></div></div>';
		html += '<div class="sum"><b>${3}</b> người</div><div class="score1">';	            
		html += '<div class="scoredo" rel="${5}">${4} <b>0%</b></div>';
		html += '<div class="scorebar" rel="${5}">';
		html += '</div></div></div><div class="w3"></div>';	        
	    
	    html = html.replace("${0}", number);
	    html = html.replace("${1}", title);
	    if(title.length > 30){
	    	html = html.replace("${_1}", title.substring(0,30));
	    }else{
	    	html = html.replace("${_1}", title);
	    }
//	    if(entryCount > 0){
//	    	html = html.replace("${2}", entryCount);
//	    }
	    html = html.replace("${3}", userCount);
	    html = html.replace("${4}", status);
	    html = html.replace(/\$\{5\}/g, id);
	    
	    return html;
	}
	
    GoalManager.findGoalByTitle("", function(result){
		if(result){			
			bindAutocomplete(result);
		}
	});

    function bindAutocomplete(data){
    	jQuery("input#newGoalTitle").autocomplete(data, {
    		minChars: 0,
    		width: 495,
    		scrollHeight: 500,
    		matchContains: "word",
    		delay: 500
    	});
    } 
    
});